using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesAdminClaimantsListing : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;    
    protected DataObj CurPageDataObj = new DataObj();

    #region CurrentPageIndex
    protected int CurrentPageIndex
    {
        get
        {
            return (int)ViewState["CurrentPageIndex"];
        }

        set
        {
            ViewState["CurrentPageIndex"] = value;
        }
    }
    #endregion 

    #region AddMessage
    protected string AddMessage
    {
        get
        {
            return ViewState["AddMessage"].ToString();
        }

        set
        {
            ViewState["AddMessage"] = value;
        }
    }
    #endregion

    #region ResultTable
    protected DataTable ResultTable
    {
        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get
        {
            return (ArrayList)ViewState["GridViewHeader"];
        }

        set
        {
            ViewState["GridViewHeader"] = value;
        }
    }
    #endregion

    #endregion

    #region Events

    #region Page_Load
    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        if (!IsPostBack)
        {
            this.CurrentPageIndex = 0;  // set to 0

            this.SwitchLanguage();
            this.PageComponentSetup();
            this.LoadDataBinding();
        } 
    }
    #endregion

    #region DropDownList_ByEntity_SelectedIndexChanged
    protected void DropDownList_ByEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
        {
            GonzalesCompanies ResultList = CurCompanyManager.GetCompanyByEntityID(this.DropDownList_ByEntity.SelectedValue);

            if (ResultList != null)
            {
                this.DropDownList_ByCompany.Items.Clear();
                this.DropDownList_ByCompany.Items.Add(new ListItem("", ""));

                for (int x = 0; x < ResultList.Count; x++)
                {
                    this.DropDownList_ByCompany.Items.Add(new ListItem(ResultList[x].CompanyName, ResultList[x].InternalID));
                }
            }
            else
            {
                this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.DropDownList_ByEntity_SelectedIndexChanged] : Failed on CurCompanyManager.GetCompanyByEntityID('" + this.DropDownList_ByEntity.SelectedValue + "') : " + CurCompanyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }

            if(this.DropDownList_ByEntity.SelectedValue == this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.FromCountry.InternalID)
                this.DropDownList_ByCompany.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.InternalID).Selected = true;
        }

        #region Filter the company by Finance Admin
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultCompanies = CurUserManager.GetCompanyByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultCompanies != null)
                {
                    int x = 1;

                    while (x < this.DropDownList_ByCompany.Items.Count)
                    {
                        bool Matched = false;

                        for (int y = 0; y < ResultCompanies.Count; y++)
                        {
                            if (ResultCompanies[y].InternalID.CompareTo(this.DropDownList_ByCompany.Items[x].Value) == 0)
                            {
                                Matched = true;
                                break;
                            }
                        }

                        if (!Matched)
                        {
                            this.DropDownList_ByCompany.Items.RemoveAt(x);
                        }
                        else
                        {
                            x++;
                        }
                    }
                }
            }
          
        }
        #endregion

    }
    #endregion

    #region DropDownList_ByCompany_SelectedIndexChanged
    protected void DropDownList_ByCompany_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.DropDownList_ByCompany.SelectedValue.Length > 0)
        {
            this.LoadDataBinding();
        }
    }
    #endregion

    #region DropDownList_SortBy_SelectedIndexChanged
    protected void DropDownList_SortBy_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView, this.CurrentPageIndex);
        }
    }
    #endregion

    #region DropDownList_SortOrder_SelectedIndexChanged
    protected void DropDownList_SortOrder_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView, this.CurrentPageIndex);
        }
    }
    #endregion

    #region GridViewResult_PageIndexChanging
    protected void GridViewResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        if (this.ResultTable != null)
        {
            this.CurrentPageIndex = e.NewPageIndex;

            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView, this.CurrentPageIndex);
        }
    }
    #endregion

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            for (int i = 0; i < this.GridViewHeader.Count; i++)
            {
                cells[i].Text = this.GridViewHeader[i].ToString();
            }
        }
    }
    #endregion

    #region Button Add New User
    protected void Button_Add_Click(object sender, EventArgs e)
    {
        if (DropDownList_ByCompany.SelectedValue.CompareTo("") != 0)
        {
            Response.Redirect("GonzalesAdminClaimantsDetail.aspx?id=AddNew&companyid=" + DropDownList_ByCompany.SelectedValue);
        }
        else
            this.ShowErrorMessage(this.AddMessage);
    }
    #endregion

    #region Button_Import_Click
    protected void Button_Import_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.FileUploadSource.PostedFile != null && this.FileUploadSource.PostedFile.FileName.Length > 0)
            {
                FileFactory.FileFactory ff = new FileFactory.FileFactory(this.CurrentPrivateSession);
                if (ff.StartWatching(this.FileUploadSource.PostedFile.InputStream, "E", this.DropDownList_ByEntity.SelectedValue))
                    this.LoadDataBinding();
            }
            else
            {
                //this.ShowErrorMessage("Invalid File");
            }
        }
        catch (Exception)
        {
            // do nothing
        }
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        
        // setup entity
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin)
        {
            #region Power Admin
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurEntityManager.GetAllEntity();
                if (ResultList != null)
                {
                    this.DropDownList_ByEntity.Items.Add(new ListItem("", ""));
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurEntityManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                }
            }

            //Added by Agnes [13 Jul 2009] - set the default country. 
            // Edited 20130502: FindEntity by entity of user logged on to set default.
            this.DropDownList_ByEntity.Items.FindByValue(this.CurrentPrivateSession.CurrentLoggedOnUser.FromCompany.Entity.InternalID).Selected = true;
            #endregion
        }
        else
        {
            #region Finance Admin

            using (UserManager CurManager = new UserManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurManager.GetEntityByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultList != null)
                {
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        if (!this.DropDownList_ByEntity.Items.Contains(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID)))
                        {
                            this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                        }
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }

        if (Request.QueryString["entity"] != null && Request.QueryString["company"] != null)
        {
            this.DropDownList_ByEntity.SelectedItem.Selected = false;
            this.DropDownList_ByEntity.Items.FindByValue(Request.QueryString["entity"]).Selected = true;

            this.DropDownList_ByEntity_SelectedIndexChanged(null, null);

            this.DropDownList_ByCompany.Items.FindByValue(Request.QueryString["company"]).Selected = true;
        }
        else
        {

            this.DropDownList_ByEntity_SelectedIndexChanged(null, null);
        }
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Button_Add.Text = CurLanguageFactory.DisplayValue("Add");

                this.GridViewHeader = new ArrayList();
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("EmployeeIDWithLink"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ADName"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ApprovingLimit"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ApprovingRoute"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("StopBit"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Name"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Title"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("Email"));

                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("EmployeeIDWithLink"), this.CurPageDataObj.EmployeeID));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ADName"), this.CurPageDataObj.ADName));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Name"), this.CurPageDataObj.DisplayName));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Title"), this.CurPageDataObj.Title));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("Email"), this.CurPageDataObj.Email));

                this.DropDownList_SortBy.SelectedIndex = 1;

                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ASC"), "ASC"));
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("DESC"), "DESC"));

                this.AddMessage = CurLanguageFactory.DisplayValue("AddMessage");
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesMyClaims.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        // only when is selected from the drop down
        //if (this.DropDownList_ByCompany.SelectedIndex > 0)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                SystemUsers ResultObj = CurUserManager.GetUsersByCompany(this.DropDownList_ByCompany.SelectedValue, true);

                if (ResultObj != null)
                {
                    this.ResultTable = new DataTable();
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.InternalID, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EmployeeID, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.EmployeeIDWithLink, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ADName, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.DisplayName, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.Title, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.Email, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ApprovingLimit, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.ApprovingRoute, Type.GetType("System.String")));
                    ResultTable.Columns.Add(new DataColumn(this.CurPageDataObj.StopBit, Type.GetType("System.String")));

                    for (int x = 0; x < ResultObj.Count; x++)
                    {
                        DataRow RowObj = ResultTable.NewRow();

                        RowObj[this.CurPageDataObj.InternalID] = ResultObj[x].InternalID;
                        RowObj[this.CurPageDataObj.EmployeeID] = ResultObj[x].EmployeeID;
                        RowObj[this.CurPageDataObj.EmployeeIDWithLink] = "<a class='GridViewLink' href='GonzalesAdminClaimantsDetail.aspx?id=" + ResultObj[x].InternalID + "'>" + ResultObj[x].EmployeeID + "</a>";
                        RowObj[this.CurPageDataObj.ADName] = ResultObj[x].EmailID;
                        RowObj[this.CurPageDataObj.DisplayName] = ResultObj[x].DisplayName;
                        RowObj[this.CurPageDataObj.Title] = ResultObj[x].JobTitle;
                        RowObj[this.CurPageDataObj.Email] = ResultObj[x].Email;
                        RowObj[this.CurPageDataObj.ApprovingLimit] = (ResultObj[x].ApprovingLimit > 0) ? ResultObj[x].ApprovingCurrency.InternalID + " " + ResultObj[x].ApprovingLimit.ToString(GonzalesGeneralVariables.CurrencyFormat) : "";
                        RowObj[this.CurPageDataObj.ApprovingRoute] = ClaimManager.GetApprovingRoute(ResultObj[x].AppRoute);
                        RowObj[this.CurPageDataObj.StopBit] = (ResultObj[x].ApprovalCheckPoint) ? "<img src='" + GonzalesImages.Icon_Checked + "'>" : "";

                        ResultTable.Rows.Add(RowObj);
                    }
                }
                else
                {
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.LoadData] : Failed at CurUserManager.GetUsersByCompany() : " + CurUserManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }
        }
    }

    #endregion

    #region LoadDataBinding
    protected void LoadDataBinding()
    {
        this.LoadData();
        if (this.ResultTable != null)
        {
            DataView ResultView = new DataView(this.ResultTable);
            ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
            this.BindData(ResultView);
        }
    }
    #endregion

    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    #endregion

    #region Class: DataObj
    protected class DataObj
    {
        public readonly string InternalID = "InternalID";
        public readonly string EmployeeID = "EmployeeID";
        public readonly string EmployeeIDWithLink = "EmployeeIDWithLink";
        public readonly string ADName = "ADName";
        public readonly string DisplayName = "Name";
        public readonly string Title = "Title";
        public readonly string Email = "Email";
        public readonly string ApprovingLimit = "ApprovingLimit";
        public readonly string ApprovingRoute = "ApprovingRoute";
        public readonly string StopBit = "StopBit";
    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

}
